package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.entity.Employee;
import com.itheima.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    // 读取固定盐
    @Value("${reggie.salt}")
    private String salt;

    @RequestMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee) {
        //1. 将页面提交的密码password进行MD5加密处理
        String password = employee.getPassword();
        password += salt;  // 用户输入的密码拼接固定盐
        password = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
        //2. 根据页面提交的用户名username查询数据库
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername, employee.getUsername());
        Employee emp = employeeService.getOne(queryWrapper);
        //3. 如果没有查询到, 则返回登陆失败结果
        if (emp == null) {
            return R.error("账号或密码错误,请重试");
        }
        //4. 如果查到但密码不一致, 则返回登陆失败结果
        if (!emp.getPassword().equals(password)) {
            return R.error("账号或密码错误,请重试");
        }
        //5. 查看员工状态, 如果已禁用, 返回员工禁用结果
        if (emp.getStatus() != 1) {
            return R.error("该账户已禁用");
        }
        //6. 登陆成功, 将员工ID放入Session域并返回登陆成功结果
        request.getSession().setAttribute("employee", emp.getId());
        return R.success(emp);
    }

    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest httpServletRequest) {
        httpServletRequest.getSession().removeAttribute("employee");
        /*
            删除session的数据的两种方法
                1. 删除session中的一个键值对 session.removeAttribute("employee");
                2. 删除session对象 session.invalidate();
         */
        httpServletRequest.getSession().invalidate();
        return R.success("退出成功");
    }

    @PostMapping
    public R<String> save(HttpServletRequest request, @RequestBody Employee employee) {
        log.info("需要新增员工的员工信息为{}", employee.toString());
        employee.setPassword(DigestUtils.md5DigestAsHex(("123456" + salt).getBytes(StandardCharsets.UTF_8)));
        // md5加密方法需要byte[] 数组
/*        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        employee.setCreateUser((Long) request.getSession().getAttribute("employee"));
        employee.setUpdateUser((Long) request.getSession().getAttribute("employee"));*/
        employeeService.save(employee);   //这个位置会触发 元数据处理器, 自动插入填充操作.
        return R.success("添加员工成功");
    }

    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        log.info("页面传递过来的参数page:{}, pageSize:{}, name:{}", page, pageSize, name);
        //创建分页构造器
        Page  pageInfo = new Page(page, pageSize);
        //创建条件构造器
        LambdaQueryWrapper<Employee> employeeLambdaQueryWrapper = new LambdaQueryWrapper<>();
        employeeLambdaQueryWrapper.like(StringUtils.isNotEmpty(name), Employee::getName, name);
        employeeLambdaQueryWrapper.orderByDesc(Employee::getUpdateTime);
        //查询
        employeeService.page(pageInfo, employeeLambdaQueryWrapper);
        return R.success(pageInfo);
    }

    @PutMapping
    public R<String> update(HttpServletRequest request, @RequestBody Employee employee) {
        log.info(employee.toString());
/*        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser((Long) request.getSession().getAttribute("employee"));*/
        employeeService.updateById(employee); //这个位置会触发 元数据处理器, 自动更新填充操作.
        return R.success("修改成功");
    }

    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id) {
        log.info("按照ID查询员工信息");
        Employee employee = employeeService.getById(id);
        if (employee != null) {
            return R.success(employee);
        }
        return R.error("员工不存在,请重试");
    }

}
